package com.example.wanandroid.controller;

import com.example.wanandroid.pojo.TbCollection;
import com.example.wanandroid.result.Result;
import com.example.wanandroid.result.ResultUtil;
import com.example.wanandroid.service.CollectionService;
import com.example.wanandroid.service.ViewService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @Desc TODO
 * @Author 小强
 * @Date 2020/4/19 13:58
 */
@RestController
public class CollectionController {
    @Autowired
    CollectionService collectionService;
    @Autowired
    ViewService viewService;

    /**
     * 添加收藏或取消收藏
     *
     * @param request
     * @param questionId
     * @return
     */
    @PostMapping("/collection/addOrCancel")
    public Result addOrCancel(HttpServletRequest request, long questionId) {
        Long userid = (Long) request.getAttribute("userid");
        TbCollection collection = collectionService.selectByQuestionUserId(questionId, userid);
        if (collection == null) {
            //未收藏，添加收藏
            collection = new TbCollection();
            collection.setQuestionId(questionId);
            collection.setUserid(userid);
            collectionService.insert(collection);
            return ResultUtil.success("收藏成功");
        } else {
            //已收藏，删除收藏
            collectionService.deleteByPrimaryKey(collection.getId());
            return ResultUtil.success("取消收藏成功");
        }
    }

    /**
     * 我的收藏列表
     *
     * @param request
     * @return
     */
    @GetMapping("/collection/getMyCollectionList")
    public Result getMyCollectionList(HttpServletRequest request, Integer page, Integer pageSize) {
        if (page == null) page = 1;
        if (pageSize == null) pageSize = 20;
        Long userid = (Long) request.getAttribute("userid");
        PageInfo<HashMap<String, Object>> pageInfo = collectionService.getByCollectionList(userid, page, pageSize);
        return ResultUtil.success(pageInfo);
    }

    /**
     * 是否收藏
     */
    @GetMapping("/collection/isCollection")
    public Result isCollection(HttpServletRequest request, Long questionId) {
        Long userid = (Long) request.getAttribute("userid");
        TbCollection collection = collectionService.selectByQuestionUserId(questionId, userid);
        return ResultUtil.success(collection != null);
    }


}
